var readline = require('readline');
var fs = require('fs');

var __etcHosts = "/etc/hosts";

function getIpFromEtchosts(name, cb) {
	var rl = readline.createInterface({
		input: fs.createReadStream(__etcHosts)
	});
	var str;
	rl.on('line', function(line) {
		str = line.replace(/\t/g, ' ');
		str = str.replace(/\s+/g, ' ');
		str = str.trim();
		var list = str.split(' ');
		var ip = list.splice(0, 1)[0];
		if (list.indexOf(name) >= 0) {
			cb(null, ip);
			cb = null;
			rl.close();
			return;
		}
	});

	rl.on('close', function() {
		cb && cb(null, null); // not found
	})
}

function getIpFromEtchosts_2(name) {
	return new Promise(function(fulfil, reject) {
		getIpFromEtchosts(name, function(err, result) {
			fulfil({
				err: err,
				ip: result
			});
		});
	});
}


//------------------test-------------------
// var __name = 'www.google.com';
// getIpFromEtchosts(__name, function(err, result) {
// 	if (err) {
// 		console.log('err:' + err);
// 	} else {
// 		console.log('/etc/hosts ' + __name + '=' + result);
// 	}
// });

// cfg = {
// 	redis: __name
// }

// getIpFromEtchosts_2(__name)

// .then(function(result) {
// 	cfg.redis = result;
// 	console.log(cfg);
// });

module.exports = {
	getIp: getIpFromEtchosts,
	getIp2: getIpFromEtchosts_2
}


//------------------dns test-------------------
// var dns = require('dns');
// dns.resolve4(__name, function(err, addresses) {
// 	if (err) throw err;
// 	console.log('addresses: ' + JSON.stringify(addresses));
// 	addresses.forEach(function(a) {
// 		dns.reverse(a, function(err, hostnames) {
// 			if (err) {
// 				throw err;
// 			}
// 			console.log('reverse for ' + a + ': ' + JSON.stringify(hostnames));
// 		});
// 	});
// });